package com.code.petapp.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import androidx.core.app.ActivityCompat;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.code.petapp.R;
import com.code.petapp.bean.UserBean;
import com.code.petapp.databinding.ActivityPersonBinding;
import com.code.petapp.fragment.MyFragment;
import com.code.petapp.http.HttpListener;
import com.code.petapp.util.MediaUtils;
import com.code.petapp.util.SPCommonUtils;
import com.code.petapp.util.UploadUtils;
import com.code.petapp.util.UserUtils;
import com.code.petapp.util.VersionUtils;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;

import java.io.File;
import java.util.ArrayList;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class PersonActivity extends BaseActivity implements OnResultCallbackListener<LocalMedia> {
    ActivityPersonBinding binding;
    public static final String TAG = "PersonActivity";
    private String imgUrl;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityPersonBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        Glide.with(this).load(R.drawable.img_juan)
                .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                .into(binding.imgAvatar);
         load();
         setImg();
         setSave();
         binding.cancel.setOnClickListener(v -> finish());

        // Set EdgeToEdge
    }
    private void load(){
        UserUtils.selectById(SPCommonUtils.getInstance().getToken(), SPCommonUtils.getInstance().getUserId(), new HttpListener<>() {
            @Override
            public void success(UserBean bean) {
                binding.name.setText(bean.getName());
                binding.username.setText(bean.getUsername());
                binding.phone.setText(bean.getPhone());
                binding.email.setText(bean.getEmail());
                Glide.with(PersonActivity.this)
                        .load(bean.getAvatar())
                        .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                        .into(binding.imgAvatar);
            }

            @Override
            public void error(int code, String error) {
                toastShortShow(error);
            }
        });
    }
    private void setSave(){
        binding.save.setOnClickListener(v -> {
            String name = binding.name.getText().toString();
            String phone = binding.phone.getText().toString();
            String email = binding.email.getText().toString();
            if(name.isEmpty() || phone.isEmpty() || email.isEmpty()){
                toastShortShow("请填写完整信息");
            }else{
                binding.save.setEnabled(false);
                UserBean userBean = new UserBean();
                userBean.setName(name);
                userBean.setPhone(phone);
                userBean.setEmail(email);
                userBean.setAvatar(imgUrl);
                userBean.setId(SPCommonUtils.getInstance().getUserId());
                UserUtils.update(SPCommonUtils.getInstance().getToken(), userBean, new HttpListener<>() {
                    @Override
                    public void success(String object) {
                        SPCommonUtils.getInstance().setName(name);
                        SPCommonUtils.getInstance().setPhone(phone);
                        SPCommonUtils.getInstance().setEmail(email);
                        toastShortShow("修改成功");
                        finish();
                    }

                    @Override
                    public void error(int code, String error) {
                        toastShortShow(error);
                    }
                });
            }
        });
    }
    private void setImg() {
        binding.imgAvatar.setOnClickListener(view -> mediaSale());
    }

    /**
     * 图片视频选择
     */
    private void mediaSale() {
        boolean isAllGranted = VersionUtils.Companion.checkPermissionAllGranted(VersionUtils.Companion.getPermission(), this);
        Log.d("ZZ", "isAllGranted:" + isAllGranted);
        if (isAllGranted) {
            MediaUtils.getPhoto(this, 1, this);
        } else {
            ActivityCompat.requestPermissions(this, VersionUtils.Companion.getPermission(), 10000);
        }
    }

    @Override
    public void onResult(ArrayList<LocalMedia> mediaVideo) {
        if (!mediaVideo.isEmpty()) {
            for (int i = 0; i < mediaVideo.size(); i++) {
                LocalMedia localMedia = mediaVideo.get(i);
                String realFilePath;
                if (localMedia.isCompressed()) {
                    realFilePath = localMedia.getCompressPath();
                } else if (localMedia.isCut()) {
                    realFilePath = localMedia.getCutPath();
                } else {
                    realFilePath = localMedia.getRealPath();
                }
                Log.d(TAG, "realFilePath:" + realFilePath);
                if (!TextUtils.isEmpty(realFilePath)) {
                    File file = new File(realFilePath);
                    RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), file);
                    MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
                    UploadUtils.upload(SPCommonUtils.getInstance().getToken(), body, new HttpListener<>() {
                        @Override
                        public void success(String data) {
                            imgUrl = data;
                            Log.d("src is:", data);
                            Glide.with(PersonActivity.this)
                                    .load(data)
                                    .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                                    .into(binding.imgAvatar);
                        }

                        @Override
                        public void error(int code, String error) {
                            toastShortShow(error);
                        }
                    });
                }
            }
        }
    }

    @Override
    public void onCancel() {

    }
}